package com.exercise;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;

public class RankHolder {

    private static final int CRAFTSMAN_RANK_TYPE = 1;

    private class RankBean<T extends Number>{

        private final long holderId; //工匠id，玩家id，根据排行榜不同来做
        private final T rankRelatedValue;

        public RankBean(long holderId, T rankRelatedValue) {
            this.holderId = holderId;
            this.rankRelatedValue = rankRelatedValue;
        }
    }

    private List<RankBean<Double>> craftsmanRankList = new ArrayList<>();

    private Comparator<RankBean<Double>> craftsmanRankComparator = (e1,e2)->{
        return (int) (e1.rankRelatedValue - e2.rankRelatedValue);

    };
    private ReadWriteLock craftsmanRankListLock = new ReentrantReadWriteLock();


    public void updateRank(int rankType,long holderId,Double rankRelatedValue){

        if(rankType == CRAFTSMAN_RANK_TYPE) {
            craftsmanRankListLock.writeLock().lock();

            //如果排行榜里有该工匠   处理 排序。。。。。

            //如果排行榜里没该工匠   处理  排序。。。。


            craftsmanRankListLock.writeLock().unlock();
        }
    }


    public void getCraftsmanRankByCraftsmanId(){
        craftsmanRankListLock.readLock().lock();

        //处理

        craftsmanRankListLock.readLock().unlock();

    }

    /**
     * warning : unsafe !!!!!!!!!!
     * @return
     */
    public List<RankBean<Double>> getCraftsmanRanks(){
      return craftsmanRankList;
    }

    public void forEachReadCraftsmanRank(Function<RankBean<Double>,Void> function){
        craftsmanRankListLock.readLock().lock();

        for(RankBean<Double> rank:craftsmanRankList){
            function.apply(rank);
        }

        craftsmanRankListLock.readLock().unlock();
    }

}
